<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\know\validate;

use app\know\model\TeachingMaterialModel;
use think\Validate;
use think\facade\Log;

class TeachingMaterialValidate extends Validate
{
    protected $rule = [
        'name' => 'require|min:1|checkName',
        'year' => 'require|length:4',
        'subject_code' => 'require|min:1',
		'grade_code' => 'require|min:1',
        'id' => 'require|gt:0',
    ];

    protected $message = [
        'name.require' => '名称为必填项',
        'name.min' => '名称不能为空',
        'year.require' => '年份为必填项',
        'year.min' => '年份不能为空',
        'subject_code.require' => '科目为必填项',
        'subject_code.min' => '科目不能为空',
        'grade_code.require' => '年级为必填项',
        'grade_code.min' => '年级不能为空',		
        'id.require' => 'id不能为空',
    ];

    protected $scene = [
        'add'  => ['name', 'year', 'subject_code', 'grade_code'],
        'edit' => ['id'],
        'delete' => ['id'],
    ];

    // 自定义验证规则
    // 同一类型下key不重复，value不重复
    protected function checkName($value, $rule, $data)
    {
        $model = new TeachingMaterialModel();
        $item  = $model->where('name', $data['name'])
                       ->find();
        Log::debug('TeachingMaterialValidate---' . $model->getLastSql());
        if (empty($item)) {
            return true;
        } else {
            return $item['name'] . "---已经存在---";
        }
    }
}